package org.unicat.serviceedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.unicat.commonutils.ResultCode;
import org.unicat.servicebase.exceptionHandler.GuliException;
import org.unicat.serviceedu.entity.EduChapter;
import org.unicat.serviceedu.entity.EduVideo;
import org.unicat.serviceedu.entity.vo.ChapterVo;
import org.unicat.serviceedu.entity.vo.VideoVo;
import org.unicat.serviceedu.mapper.EduChapterMapper;
import org.unicat.serviceedu.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.unicat.serviceedu.service.EduVideoService;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author unicat
 * @since 2022-02-22
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduChapterService chapterService;

    @Autowired
    private EduVideoService videoService;

    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {

        List<ChapterVo> resultList = new ArrayList<>();

        // 根据课程id查询课程里面的所有章节并排序
        List<EduChapter> chapterList = chapterService.list(new QueryWrapper<EduChapter>()
                .eq("course_id", courseId)
                .orderByAsc("sort"));
        //根据课程id查询课程里面的所有小节并排序
        List<EduVideo> videoList = videoService.list(new QueryWrapper<EduVideo>()
                .eq("course_id", courseId)
                .orderByAsc("sort"));
        // 遍历查询小节list集合，进行封装
        for (EduChapter chapter : chapterList) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter, chapterVo);

            resultList.add(chapterVo);

            List<VideoVo> childrenList = new ArrayList<>();
            for (EduVideo video : videoList) {
                if (video.getChapterId().equals(chapter.getId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video, videoVo);
                    childrenList.add(videoVo);
                }
            }
            chapterVo.setChildren(childrenList);
        }

        return resultList;
    }

    @Override
    public boolean removeChapterById(String courseId) {
        int count = videoService.count(new QueryWrapper<EduVideo>().eq("chapter_id", courseId));
        if (count > 0) {
            throw new GuliException(ResultCode.ERROR, "该章节含有小节，不能删除");
        }
        return this.removeById(courseId);
    }

    @Override
    public boolean removeByCourseId(String courseId) {
        QueryWrapper<EduChapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        int count = baseMapper.delete(queryWrapper);
        return count > 0;
    }
}
